package com.haiheng.module_main.mode

import android.text.TextUtils
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.haiheng.common.api.API
import com.haiheng.common.bean.BookInfoBean
import com.haiheng.common.bean.UserInfoBean
import com.haiheng.common.bean.res.BookTagBean
import com.haiheng.common.bean.res.BorrowBookTheftRes
import com.haiheng.common.bean.res.QueryBookResp
import com.haiheng.common.constant.RourePage
import com.haiheng.library.log.LogUtils
import com.haiheng.library.log.LogWriter
import com.haiheng.library_base.http.Domain
import com.haiheng.library_base.http.HttpRequest
import com.haiheng.library_base.http.postJson
import com.haiheng.library_base.model.BaseViewModel
import com.haiheng.library_base.utils.DateUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2022/9/22 0022
 * @Version: 1.0
 */
class BorrowReturnViewModel:BaseViewModel() {
    val bookInfolist = MutableLiveData<List<BookInfoBean>>()
    val borrowSuccessNum = MutableLiveData<Int>(0)
    val borrowFailNum = MutableLiveData<Int>(0)
    var expireBookNum = MutableLiveData<Int>(0) //超期数量
    var returnSuccessNum = MutableLiveData<Int>(0)//还书成功数量
    var returnFailNum = MutableLiveData<Int>(0)//还书失败数量

    val CHANGE_SHELFT_ERROR_CODE = "-88"//自定义修改防盗位错误码
    /**
     * 续借
     */
    fun renewBook(bookList : List<BookInfoBean>?,patronSn: String){
        viewModelScope.launch {
            if (bookList != null) {
                bookList.forEach {
                    if (it != null && !TextUtils.isEmpty(it.bookSn) && it.isSelect){
                        val request = HttpRequest(API.POST_PATH)
                            .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                            .setJsonObjec(RequestDataHelper.getRennewBookReqData(it.bookSn,patronSn))
                        var response = postJson<QueryBookResp>(request)
                        if (response != null && response.errorCode.equals("0")){
                            it.borrowStatus = "再借已续借"
                            it.needReturnTime = response?.result?.needReturnTime
                            it.needReturnDate = response?.result?.needReturnTime
                        }else{
                            it.borrowStatus = "续借失败"
                        }
                        if (!DateUtils.compareCurrentDate(it.needReturnTime,
                                DateUtils.DATE_FORMAT_2)){
                            it.borrowStatus = "超期"
                        }
                        it.message = response?.message
                        it.errorCode = response?.errorCode
                    }
                }
                bookInfolist.postValue(bookList!!)
            }
        }
    }

    /**
     * 查询超期文献数量
     */
    fun queryExpireNum(bookSnList:List<String>){
        viewModelScope.launch {

            var expireNum = 0
            bookSnList.forEach {
                if (it != null && !TextUtils.isEmpty(it)){
                    val request = HttpRequest(API.POST_PATH)
                        .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                        .setJsonObjec(RequestDataHelper.getQueryBookInfoData(it))
                    var response = postJson<QueryBookResp>(request){

                    }
                    if (response != null && response.errorCode.equals("0")){
                        response.result?.let { it1 ->
                            if (!DateUtils.compareCurrentDate(it1.needReturnDate,
                                    DateUtils.DATE_FORMAT_2)){
                                LogUtils.e("已过期")
                                expireNum++
                            }else{
                                LogUtils.e("未过期")
                            }
                        }
                    }
                }
            }
            expireBookNum.postValue(expireNum)
        }
    }

    /**
     * 查询续借列表
     */
    fun queryRenewBookList(userInfoBean: UserInfoBean){
        viewModelScope.launch {
            var bookList = mutableListOf<BookInfoBean>()
            var bookSnList = userInfoBean.borrowedItemSnList
            bookSnList?.forEach {
                val bookInfoReq = HttpRequest(API.POST_PATH)
                    .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                    .setJsonObjec(RequestDataHelper.getQueryBookInfoData(it))
                var bookInfoRes = postJson<QueryBookResp>(bookInfoReq){}
                if (bookInfoRes.errorCode.equals("0")){
                    var bookInfo = bookInfoRes.result as BookInfoBean
                    bookInfo.needReturnTime = bookInfo.needReturnDate
                    bookInfo.errorCode = bookInfoRes.errorCode
                    bookInfo.message = bookInfoRes.message
                    if ("2".equals(bookInfo.circulationStatusValue)){
                        bookInfo.borrowStatus = "在借"
                    }else if("1".equals(bookInfo.circulationStatusValue)){
                        bookInfo.borrowStatus = "在馆"
                    }else if("0".equals(bookInfo.circulationStatusValue)){
                        bookInfo.borrowStatus = "不可借"
                    }
                    if (!DateUtils.compareCurrentDate(bookInfo.needReturnDate,
                            DateUtils.DATE_FORMAT_2)){
                        bookInfo.borrowStatus = "超期"
                    }
                    bookList.add(bookInfo)
                }
            }
            bookInfolist.postValue(bookList)
        }
    }



    //修改防盗位失败的书籍，自动还掉
    fun dealWithFailBook(failBookList: MutableList<BookInfoBean>, patronSn: String) {
        viewModelScope.launch {
            failBookList.forEach {
                if (it != null && it.bookSn != null && it.bookSn!!.isNotBlank()){
                    val bookInfoReq = HttpRequest(API.POST_PATH)
                        .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                        .setJsonObjec(RequestDataHelper.getQueryBookInfoData(it.bookSn!!))
                    var bookInfoRes = postJson<QueryBookResp>(bookInfoReq){}
                    LogUtils.d("net ${it.bookSn} 自动还书结果：${bookInfoRes.toJson()}")
                    val request = HttpRequest(API.POST_PATH)
                        .putHeader(Domain.KEY_NAME, Domain.VALUE_ACS)
                        .setJsonObjec(RequestDataHelper.getRetunBookReqData(it.bookSn!!,patronSn))
                    var response = postJson<QueryBookResp>(request)
                    LogUtils.d("net ${it.bookSn} 自动还书结果：${response}")
                }
            }
        }
    }

}